package vtt.android.lichphatsongbongda.fragments;

import vtt.android.library.utils.VttGA;
import vtt.android.lichphatsongbongda.R;
import vtt.android.lichphatsongbongda.dialogs.DialogManager;
import vtt.android.lichphatsongbongda.dialogs.DialogManager.IDialogListener;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.google.android.gms.ads.AdView;

import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;

/**
 * A placeholder fragment containing a simple view.
 */
public class SopcastLinkFragment extends BaseWebFragment {
	
	private View mLPSRootView;
	private String fontSize;
	
	private DownloadManager manager;
	/**
	 * Returns a new instance of this fragment for the given section number.
	 */
	public static SopcastLinkFragment newInstance(int sectionNumber) {
		SopcastLinkFragment fragment = new SopcastLinkFragment();
		Bundle args = new Bundle();
		args.putInt(ARG_SECTION_NUMBER, sectionNumber);
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		manager = (DownloadManager)  mParentAct.getSystemService(Context.DOWNLOAD_SERVICE);
	}
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		fontSize = (mParentAct.getResources().getDisplayMetrics().density  * 120) + "%";
		log.d("VTT>>> fontSize " + fontSize);
		
		mLPSRootView = inflater.inflate(R.layout.fragment_cm_webview, container, false);
		mProgressBar = (SmoothProgressBar) mLPSRootView.findViewById(R.id.progressbar_loading);

		// Look up the AdView as a resource and load a request.
		AdView adView = (AdView) mLPSRootView.findViewById(R.id.adView);
		// load admob
		loadAdmob(adView);
				
		// init webview
		mWebView = (WebView) mLPSRootView.findViewById(R.id.webView1);
		// init common webview
		initCommonWebview();
		
		// prevent javascript of this page
		mWebView.getSettings().setJavaScriptEnabled(false);
		mWebView.setWebViewClient(new WebClient());
		mWebView.setLongClickable(false);
		//mWebView.addJavascriptInterface(new AndroidBridge(), "Android");
		mWebView.setInitialScale(115);
		
		if (Build.VERSION.SDK_INT >= 11){
            mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
		
		// If there is a previous instance restore it in the webview
	    mWebView.loadUrl(getString(R.string.url_sopcast_1));	
	    // TODO request HTML
	    //new SopcastLinkTask().execute(getString(R.string.url_sopcast_1));

		return mLPSRootView;
	}
	
//	@Override
//	protected void reloadPage() {
//	    new SopcastLinkTask().execute(getString(R.string.url_sopcast_1));
//	}
	
	class WebClient extends WebViewClient {

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			mProgressBar.progressiveStart();
			super.onPageStarted(view, url, favicon);
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			log.d("VTT>>> shouldOverrideUrlLoading " + url);
			
			if(url.toLowerCase().endsWith(".apk")){
                return true;
            }
			
			if(url.startsWith("sop://")){
				
				PackageManager pm = mParentAct.getPackageManager();
				Intent appStartIntent = pm.getLaunchIntentForPackage("org.sopcast.android");
				if (null != appStartIntent) {
					Uri uri = Uri.parse(url);
					appStartIntent.setData(uri);
					try {
						mParentAct.startActivity(appStartIntent);
						VttGA.sendEvent(mParentAct, "start sopcast", "start sopcast", "", 0);
					} catch (ActivityNotFoundException e) {
						Intent myAppLinkToMarket = new Intent(Intent.ACTION_VIEW, uri);
						try {
							startActivity(myAppLinkToMarket);
						} catch (ActivityNotFoundException ex) {
							VttGA.sendException(mParentAct, "Không mở được sopcast");
						}
					}
					
				} else {
					mDialogManager.showCommonDialog(DialogManager.DIALOG_TYPE_WARNING, 
							getString(R.string.msg_title_notice),
							getString(R.string.msg_sopcast_warning_install), new IDialogListener() {
								
								@Override
								public void onOkClick() {
									VttGA.sendEvent(mParentAct, "onOkClick", "close sopcast dialog", "", 0);
									/*try {
									    downloadApp(mParentAct, getString(R.string.url_sopcast_apk_link));
                                    } catch (Exception e) {
                                        if(getActivity() == null){
                                            return;
                                        }
                                        Toast.makeText(mParentAct, "Có lỗi xảy ra, tải sopcast thất bại, vui long thử lại!", 1).show();
                                        VttGA.sendException(mParentAct, "downloadApp sopcast error " + e.getMessage());
                                    }*/
								}
								
								@Override
								public void onCancelClick() {
									VttGA.sendEvent(mParentAct, "onCancelClick", "close dialog", "", 0);
								}
							});
				}
				
				return true;
			}
			
			return super.shouldOverrideUrlLoading(view, url);
		}
	}
}